package com.ikas.ai.server.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ikas.ai.server.security.TokenUser;
import com.ikas.ai.server.security.UserContextHolder;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author wuyf
 * @date 2023/10/25 17:36
 */

@Component
public class MybatisObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(originalObject));
        if (ObjectUtils.isEmpty(jsonObject)) {
            return;
        }
        //设置字段值-通过条件
        setFieldValByCondition(metaObject, jsonObject, "creator", getUserId());
        setFieldValByCondition(metaObject, jsonObject, "updater", getUserId());
        //创建时间和修改时间不用判断是否有值
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(originalObject));
        if (ObjectUtils.isEmpty(jsonObject)) {
            return;
        }
        setFieldValByCondition(metaObject, jsonObject, "updater", getUserId());
        //修改时间不用判断是否有值
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    /**
     * 获取用户信息
     * @return long
     */
    private Long getUserId() {
        TokenUser tokenUser = UserContextHolder.getTokenUser();
        return tokenUser == null ? -1L : tokenUser.getUserId();
    }

    /**
     * 设置字段值-通过条件
     * @param metaObject metaObject
     * @param jsonObject jsonObject
     * @param fieldKey 字段名称
     * @param fieldValue 字段值
     */
    private void setFieldValByCondition(MetaObject metaObject, JSONObject jsonObject,
                                        String fieldKey, Object fieldValue) {
        if (metaObject.hasSetter(fieldKey) && StringUtils.isBlank(jsonObject.getString(fieldKey))) {
            this.setFieldValByName(fieldKey, fieldValue, metaObject);
        }
    }

}